package git.soulbgm.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import git.soulbgm.config.SysConfig;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 存储元对象处理程序
 *
 * @author SoulBGM
 * @date 2022/03/21 15:35
 */
@Component
public class StorageMetaObjectHandler implements MetaObjectHandler {

    private static final String GETTER_NAME_REGION_CODE = "regionCode";
    private static final String GETTER_NAME_CREATE_TIME = "createTime";
    private static final String GETTER_NAME_UPDATE_TIME = "updateTime";
    private static final String GETTER_NAME_STARTUP_TIME = "startupTime";

    @Override
    public void insertFill(MetaObject metaObject) {
        // 插入时自动填充
        // 注意第二个参数要填写实体类中的字段名称，而不是表的列名称
        List<String> nameList = Arrays.stream(metaObject.getGetterNames()).collect(Collectors.toList());
        if (nameList.contains(GETTER_NAME_REGION_CODE)) {
            strictFillStrategy(metaObject, GETTER_NAME_REGION_CODE, SysConfig.getConfig()::getRegionCode);
        }
        if (nameList.contains(GETTER_NAME_CREATE_TIME)) {
            strictFillStrategy(metaObject, GETTER_NAME_CREATE_TIME, Date::new);
        }
        if (nameList.contains(GETTER_NAME_UPDATE_TIME)) {
            strictFillStrategy(metaObject, GETTER_NAME_UPDATE_TIME, Date::new);
        }
        if (nameList.contains(GETTER_NAME_STARTUP_TIME)) {
            strictFillStrategy(metaObject, GETTER_NAME_STARTUP_TIME, Date::new);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        List<String> nameList = Arrays.stream(metaObject.getGetterNames()).collect(Collectors.toList());
        if (nameList.contains(GETTER_NAME_UPDATE_TIME)) {
            strictFillStrategy(metaObject, GETTER_NAME_UPDATE_TIME, Date::new);
        }
    }
}
